package com.owner.demo.springbootdemo.CircuitBreaker;

import lombok.ToString;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 时间间隔计数器
 * @author lcb52
 * @date 2020-9-2
 */
@Slf4j
@ToString
public class TimeIntervalCounter {

    /**
     * 计时开始时间
     */
    private long startTime;

    /**
     * 计时器阈值
     */
    private long timeIntervalInMs;
    /**
     * 计数器上阈值
     */
    private int countThreshold;

    /**
     * 计数器
     */
    private AtomicInteger currentCount;

    public TimeIntervalCounter(long timeIntervalInMs, int countThreshold) {
        super();
        this.timeIntervalInMs = timeIntervalInMs;
        this.countThreshold = countThreshold;
        startTime = System.currentTimeMillis();
        currentCount = new AtomicInteger(0);
    }


    public int incrAndGet() {
        long currentTime = System.currentTimeMillis();
        if (ltTimeIntervalInMs(currentTime)) {
            synchronized (this) {
                if (ltTimeIntervalInMs(currentTime)) {
                    startTime = currentTime;
                    currentCount.set(0);
                }
            }
        }
        return currentCount.incrementAndGet();
    }

    public boolean ltThreshold(){
        log.info("count[{}] > maxLimit[{}], timeIntervalInMs[{}] > now[{}]", currentCount.get(), countThreshold, timeIntervalInMs, System.currentTimeMillis() - startTime);
        return currentCount.get() > countThreshold && !ltTimeIntervalInMs(System.currentTimeMillis());
    }

    public boolean ltTimeIntervalInMs(long currentTime) {
        return (startTime + timeIntervalInMs) < currentTime;
    }

    public int getCurrentCount(){
        return currentCount.get();
    }

    public /*synchronized*/ void reset(){
        currentCount.set(0);
    }

}
